package daniel.erp.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import daniel.erp.dao.IDepDao;
import daniel.erp.entity.Dep;

public class DepDao extends HibernateDaoSupport implements IDepDao {
	//查询所有部门
	public List<Dep> getAllDep() {
		@SuppressWarnings("unchecked")
		List<Dep> list = (List<Dep>) this.getHibernateTemplate().find("from Dep");
		return list;
	}
	
	public DetachedCriteria getDetachedCriteria(Dep dep1){
		DetachedCriteria c=DetachedCriteria.forClass(Dep.class);
		if(dep1!=null){
			if(dep1.getName()!=null&&dep1.getName().length()>0){
				c.add(Restrictions.like("name", dep1.getName(),MatchMode.ANYWHERE));
			}
			if(dep1.getTele()!=null&&dep1.getTele().length()>0){
				c.add(Restrictions.like("tele", dep1.getTele(),MatchMode.ANYWHERE));
			}
		}
		return c;
	}
	
	public Long getTotalDep(Dep dep1){
		DetachedCriteria c=getDetachedCriteria(dep1);
		c.setProjection(Projections.rowCount());
		List<Long> list = (List<Long>) getHibernateTemplate().findByCriteria(c);
		return list.get(0);
	}
	
	//通过查询条件查询部门
	@SuppressWarnings("unchecked")
	public Map<String, Object> getDepByQuery(Dep dep1,int page,int rows) {
		DetachedCriteria c=getDetachedCriteria(dep1);
		Map<String, Object> m=new HashMap<String, Object>();
		m.put("total", getTotalDep(dep1).toString());
		List<Dep> li=(List<Dep>) this.getHibernateTemplate().findByCriteria(c,(page-1)*rows,rows);
		m.put("rows", li);
		return m;
	}

	public void saveDep(Dep dep) {
		this.getHibernateTemplate().save(dep);
	}

	public Dep getDepById(Long id) {
		
		return this.getHibernateTemplate().get(Dep.class, id);
	}

	public void updateDep(Dep dep) {
		this.getHibernateTemplate().update(dep);
		
	}

	public void deleteDep(Long id) {
		Dep dep = this.getHibernateTemplate().get(Dep.class, id);
		this.getHibernateTemplate().delete(dep);
		
	}

}
